<?php

namespace App\Jobs;

use App\Func\MeLawCaseFunc;
use App\Imports\CasesImport;
use App\Models\ImportTask;
use App\Models\MeClient\MeClientModel;
use App\Models\MeLawCase\MeLawCasePhoneModel;
use App\Tools\Log\Log;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Database\QueryException;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;
use Ramsey\Uuid\Uuid;
use Maatwebsite\Excel\Excel as ExcelType;
use Illuminate\Support\Facades\DB;

// nohup php artisan queue:work --daemon & 命令
class ProcessCaseImport implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $timeout = 600; // 延长超时时间
    public $tries = 3;
    public $backoff = 60; // 失败重试间隔

    public $filePath;
    public $fileExt;
    public $clientId;
    public $ownerId;
    public $fileName;
    public $taskId;
    public $batchSize = 100; // 减小批次大小

    public function __construct(string $filePath, int $clientId, int $ownerId, string $fileName, string $fileExt)
    {
        $this->filePath = $filePath;
        $this->clientId = $clientId;
        $this->ownerId = $ownerId;
        $this->fileName = $fileName;
        $this->fileExt = $fileExt;

        $taskId = Uuid::uuid4()->toString();
        $this->taskId = $taskId;

        ImportTask::create([
            'file_path' => $filePath,
            'task_id' => $taskId,
            'client_id' => $clientId,
            'owner_id' => $ownerId,
            'file_name' => $fileName,
            'status' => ImportTask::STATUS_PENDING,
        ]);
    }

    public function handle()
    {
        $task = ImportTask::where('task_id', $this->taskId)->firstOrFail();
        try {
            $task->update([
                'status' => ImportTask::STATUS_PROCESSING
            ]);
            Excel::import(new CasesImport($this->clientId, $this->ownerId), $task['file_path']);
            $task->update([
                'status' => ImportTask::STATUS_SUCCESS
            ]);
        } catch (\Exception $e) {
            $errorMsg = "导入任务失败: " .$e->getFile(). $e->getMessage() . " Line: " . $e->getLine();
            $task->update([
                'status' => ImportTask::STATUS_FAILED,
                'error_log' => $errorMsg
            ]);
        } finally {
            // 确保临时文件被删除
            if (file_exists($task['file_path'])) {
                @unlink($task['file_path']);
            }
        }
    }

    public function getTaskId(): string
    {
        return $this->taskId;
    }
}